<?php


namespace Xiaoguai\DesignPattern\DP005;


abstract class AbstractSubject
{
    /**
     * @var ObserverInterface[] $observers
     */
    protected $observers = [];

    public function attach(ObserverInterface $observer): void
    {
        $this->observers[] = $observer;
    }

    public function detach(ObserverInterface $observer): void
    {
        $position = false;
        foreach ($this->observers as $index => $obs) {
            if ($obs === $observer) {
                $position = $index;
            }
        }
        if ($position !== false) {
            array_splice($this->observers, $position, 1);
        }
    }

    public function notify(): void
    {
        foreach ($this->observers as $observer) {
            $observer->update($this);
        }
    }
}